package controller;


import java.io.*;
import java.sql.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import model.KlsDocumentoTransporte;
import model.KlsEstadoDocumentoTransporte;
import model.KlsEstadoVehiculo;
import model.KlsPedido;
import model.KlsRecorrido;
import model.KlsVehiculo;


import org.hibernate.*;
import org.hibernate.engine.jdbc.LobCreator;


import javax.xml.parsers.*;
import javax.xml.xpath.*;

import org.w3c.dom.*;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import util.HibernateUtil;

import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;


public class KlsRecorridoManager {
	
	private static int ESTADO_DOC_TRANSPORTE_EN_VIAJE = 4;
	private static int ESTADO_DOC_TRANSPORTE_PROGRAMADO = 2;
	private static int VEHICULO_EN_VIAJE = 2;
	private KlsVehiculo klsVehiculo;
	


	@SuppressWarnings("unchecked")
	public List <String> devolverDatosMapa(int piVehiculo ) throws IOException, SQLException, XPathExpressionException, ParserConfigurationException, SAXException
	{
		List<KlsRecorrido> klsRecorridoList = null;

		KlsRecorrido klsRecorrido;
		Clob cbRecorrido;
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		
		try{
		
		klsRecorrido = (KlsRecorrido) session.createQuery(" from model.KlsRecorrido  dt "+
											   " where dt.klsDocumentoTransporte.klsVehiculo.idVehiculo =:idVehiculo"+
											   " and dt.klsDocumentoTransporte.klsEstadoDocumentoTransporte.idEstadoDocumentoTransporte = :estadoDocTransporte")
											   .setParameter("idVehiculo", piVehiculo)
											   .setParameter("estadoDocTransporte", ESTADO_DOC_TRANSPORTE_EN_VIAJE)
											   .uniqueResult();	
			
		
		cbRecorrido = klsRecorrido.getRecorrido();
		//InputStream is = cbRecorrido.getAsciiStream();
		//BufferedReader xml=  new BufferedReader(new InputStreamReader(is,"UTF-8" ));
		int clobLength = (int) cbRecorrido.length();
		String sXml = cbRecorrido.getSubString(1, clobLength);
		
		session.getTransaction().commit();
		return obtenerArray(sXml);
		//return obtenerArray(reader2String(xml));
		
		}
		catch(Exception e)
		{
			session.getTransaction().rollback();
			e.printStackTrace();
			return null;
			
		}
		
		
	}
	
	
	public  List <String>  obtenerArray(String pXml)throws ParserConfigurationException, SAXException, 
    IOException, XPathExpressionException {

		
		 List <String> s = new ArrayList<String>();; 
		
		 
		 DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
		    domFactory.setNamespaceAware(true); // never forget this!
		    
		    
		     
		    //InputSource is = new InputSource(pXml);
		    //is.setEncoding("UTF-8");
		    //String sXml  = reader2String(pXml);
		    ByteArrayInputStream encXML = new ByteArrayInputStream(pXml.getBytes("UTF-8"));
		    
		    DocumentBuilder builder = domFactory.newDocumentBuilder();
		    
		    
		    Document doc = builder.parse(encXML);

		    XPathFactory factory = XPathFactory.newInstance();
		    XPath xpath = factory.newXPath();
		    XPathExpression expr = xpath.compile("//start_address/text()");

		    Object result = expr.evaluate(doc, XPathConstants.NODESET);
		    NodeList nodes = (NodeList) result;
		    for (int i = 0; i < nodes.getLength(); i++) {
		        //System.out.println(nodes.item(i).getNodeValue()); 
		        s.add(nodes.item(i).getNodeValue());
		    }
		    
		     expr = xpath.compile("//end_address/text()");
		     

		     result = expr.evaluate(doc, XPathConstants.NODESET);
		     nodes = (NodeList) result;
		     
		     s.add(nodes.item(nodes.getLength()-1).getNodeValue());
		     
		    ////for (int i = 0; i < nodes.getLength(); i++) {
		    //    //System.out.println(nodes.item(i).getNodeValue()); 
		    //    s.set(i, s.get(i)+","+ nodes.item(i).getNodeValue());
		    //}
		    
		    return s;
		    
		    /*Iterator<String> iter = s.iterator();
		    while (iter.hasNext())
		      System.out.println(iter.next());*/
		    }

	
	
	

	public List <String>  grabarRecorrido(int idDocTransporte)
	{
		//TODO: falta grabar el orde en la tabla de relacion
		String sUrl = armarURL(idDocTransporte);
		KlsRecorrido klsRecorrido = new KlsRecorrido();
		KlsDocumentoTransporte klsDocumentoTransporte;

	    Calendar c = Calendar.getInstance();
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		String fecha = df.format( c.getTime());
		
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		
		klsDocumentoTransporte = (KlsDocumentoTransporte) session.get(KlsDocumentoTransporte.class, idDocTransporte);
		
		Clob recorrido;
		try {
			URL url = new URL(sUrl);
			//int iSize = url.openConnection().
			InputStream is = url.openConnection().getInputStream();
			BufferedReader reader = new BufferedReader( new InputStreamReader(is,"UTF-8" ) );
		
			//Reader readerParaParser = new BufferedReader( new InputStreamReader( is )  );
			
			String xml = reader2String(reader);
			//reader.
			
			klsRecorrido.setKlsDocumentoTransporte(klsDocumentoTransporte);

			klsRecorrido.setFecha(fecha);
			
			LobCreator lobCreator = Hibernate.getLobCreator(session);
			recorrido = lobCreator.createClob(xml);
			
			
			
			klsRecorrido.setRecorrido(recorrido);
			
			klsRecorrido.setUrl(sUrl);
			
			//GRABO RECORRIDO
			session.save(klsRecorrido);
			
			//GRABO DOCUMENTO DE TRANSPORTE MODIFICANDO ESTADO
			modificarEstadoDocTransporteYVehiculo(klsDocumentoTransporte,session);
			session.getTransaction().commit();
			
			
		} catch (MalformedURLException e) {
			session.getTransaction().rollback();
			e.printStackTrace();
			return null;
			
		} catch (IOException e) {
			session.getTransaction().rollback();
			e.printStackTrace();
			return null;
			
		} 
		catch(Exception e)
		{
			session.getTransaction().rollback();
			e.printStackTrace();
			return null;
			
		}

		return null;
		//return obtenerArray(readerParaParser);
	
	}


	private void modificarEstadoDocTransporteYVehiculo(
			KlsDocumentoTransporte klsDocumentoTransporte, Session session) {
	
		KlsEstadoDocumentoTransporte klsEstadoDocumentoTransporte = (KlsEstadoDocumentoTransporte) session.get(KlsEstadoDocumentoTransporte.class, ESTADO_DOC_TRANSPORTE_EN_VIAJE);
		KlsEstadoVehiculo klsEstadoVehiculo = (KlsEstadoVehiculo) session.get(KlsEstadoVehiculo.class, VEHICULO_EN_VIAJE);
		klsDocumentoTransporte.setKlsEstadoDocumentoTransporte(klsEstadoDocumentoTransporte);
		
		klsVehiculo = klsDocumentoTransporte.getKlsVehiculo();
		klsVehiculo.setKlsEstadoVehiculo(klsEstadoVehiculo);
		try{
		session.save(klsDocumentoTransporte);
		session.save(klsVehiculo);
		}
		catch (Exception e) {
			// TODO: handle exception
			session.getTransaction().rollback();
			e.printStackTrace();
		}
		
	}


	private String reader2String(BufferedReader reader) throws IOException {
		String xml = "";
		String s;
		int i = 0;
		while((s=reader.readLine())!= null) 
			{
			if(i>0) xml += s; 
				i++;
			}
		return xml;
	}


	private String armarURL(int idDocTransporte) {
		String sDireccionOrigen = "Medrano 951,CABA";
		String sWaypoints = "";
		String sUrl ;
		
		KlsDocumentoTransportePedidoManager klsDocumentoTransportePedidoManager = new KlsDocumentoTransportePedidoManager();
		
		//Le envio el estado del pedido 2 pendiente de entrega
		List <KlsPedido> pedidosList = klsDocumentoTransportePedidoManager.listPedidosPorDocTransporteYEstado(idDocTransporte, 2);
		
		Iterator iteraPedidos = pedidosList.iterator();
		KlsPedido  klsPedido;
		while(iteraPedidos.hasNext())
		{
			klsPedido =  (KlsPedido)iteraPedidos.next();
			if(iteraPedidos.hasNext())
				sWaypoints += klsPedido.getDireccion()+" "+klsPedido.getNumeracionDireccion()+","+klsPedido.getKlsLocalidad().getNombre()+",BA|";
			else
				sWaypoints += klsPedido.getDireccion()+" "+klsPedido.getNumeracionDireccion()+","+klsPedido.getKlsLocalidad().getNombre()+",BA";
		}
		
		
		sUrl = "http://maps.googleapis.com/maps/api/directions/xml?origin="+sDireccionOrigen+"&waypoints=optimize:true|"+sWaypoints+"&sensor=false";
		sUrl = sUrl.replace(" ","%20");
		return sUrl;
	}
	
	
	public KlsVehiculo getKlsVehiculo() {
		return klsVehiculo;
	}


	public void setKlsVehiculo(KlsVehiculo klsVehiculo) {
		this.klsVehiculo = klsVehiculo;
	}

	
	
	
	}


